<template>
  <div class="report-container">
    <el-card class="report-card">
      <template #header>
        <div class="card-header">
          <h2><el-icon><TrendCharts /></el-icon> 营业报表</h2>
          <div class="header-actions">
            <el-radio-group v-model="statsPeriod" @change="handlePeriodChange">
              <el-radio-button label="day">按日</el-radio-button>
              <el-radio-button label="week">按周</el-radio-button>
              <el-radio-button label="month">按月</el-radio-button>
            </el-radio-group>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :disabled-date="(time) => time > new Date()"
              @change="handleDateChange"
            />
          </div>
        </div>
      </template>

      <div class="summary-cards">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-card shadow="hover" class="summary-card total">
              <template #header>总营业额</template>
              <div class="amount">¥ {{ formatNumber(totalStats.total) }}</div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card shadow="hover" class="summary-card room">
              <template #header>房间收入</template>
              <div class="amount">¥ {{ formatNumber(totalStats.room) }}</div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card shadow="hover" class="summary-card snack">
              <template #header>商品收入</template>
              <div class="amount">¥ {{ formatNumber(totalStats.snack) }}</div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card shadow="hover" class="summary-card adjustment">
              <template #header>调整金额</template>
              <div class="amount">¥ {{ formatNumber(totalStats.adjustment) }}</div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card shadow="hover" class="summary-card orders">
              <template #header>订单数量</template>
              <div class="amount">{{ totalStats.orders }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="chart-container">
        <div ref="chartRef" class="chart"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { TrendCharts } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { reportAPI } from '@/api/services'

const statsPeriod = ref('day')
const chartRef = ref(null)
let chart = null
const dateRange = ref([])
const reportData = ref({
  orders: [],
  total_amount: 0,
  room_income: 0,
  snack_income: 0,
  order_count: 0
})
const loading = ref(false)

// 修改默认日期范围的计算
const defaultDateRange = computed(() => {
  const today = new Date()
  today.setDate(today.getDate() +1) // 加一天 
  const startAgo = new Date()
  startAgo.setDate(today.getDate() - 150)  // 减59天以包含当天
  return [startAgo, today]
})

// 计算统计总数
const totalStats = computed(() => {
  if (!reportData.value?.summary) return {
    total: 0,
    room: 0,
    snack: 0,
    adjustment: 0,
    orders: 0
  }

  const { summary } = reportData.value
  return {
    total: summary.total_amount || 0,
    room: summary.total_base_amount || 0,
    snack: summary.total_snack_amount || 0,
    adjustment: summary.total_adjustment || 0,
    orders: summary.order_count || 0
  }
})

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 获取周数
const getWeekNumber = (date) => {
  const d = new Date(date)
  d.setHours(0, 0, 0, 0)
  d.setDate(d.getDate() + 4 - (d.getDay() || 7))
  const yearStart = new Date(d.getFullYear(), 0, 1)
  const weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7)
  return `${d.getFullYear()}年第${weekNo}周`
}

// 获取月份
const getMonth = (date) => {
  const d = new Date(date)
  return `${d.getFullYear()}年${d.getMonth() + 1}月`
}

// 根据统计周期获取日期标识
const getDateKey = (date) => {
  const d = new Date(date)
  switch (statsPeriod.value) {
    case 'day':
      return `${d.getMonth() + 1}月${d.getDate()}日`
    case 'week':
      return getWeekNumber(d)
    case 'month':
      return getMonth(d)
    default:
      return `${d.getMonth() + 1}月${d.getDate()}日`
  }
}

// 获取报表数据
const fetchReportData = async () => {
  try {
    loading.value = true
    // 如果有选择日期范围，使用选择的日期，否则使用默认范围
    const [start, end] = dateRange.value || defaultDateRange.value
    const response = await reportAPI.getReportByDateRange(
      start.toISOString().split('T')[0],
      end.toISOString().split('T')[0]
    )
    reportData.value = response
    updateChart()
  } catch (error) {
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateChart = () => {
  if (!chart) return
  
  // 确保数据存在
  if (!reportData.value?.orders) return

  // 处理数据
  const orders = reportData.value.orders
  const dateMap = new Map() // 用于存储每天的数据

  orders.forEach(order => {
    const dateKey = getDateKey(order.start_time)

    if (dateMap.has(dateKey)) {
      const data = dateMap.get(dateKey)
      data.roomAmount += order.base_amount
      data.snackAmount += order.snack_amount
      data.adjustAmount += order.adjustment
    } else {
      dateMap.set(dateKey, {
        roomAmount: order.base_amount,
        snackAmount: order.snack_amount,
        adjustAmount: order.adjustment
      })
    }
  })

  // 排序日期
  const sortedDates = Array.from(dateMap.keys()).sort((a, b) => {
    if (statsPeriod.value === 'month') {
      return new Date(a.replace('年', '/').replace('月', '')) - new Date(b.replace('年', '/').replace('月', ''))
    }
    return 0 // 其他情况保持原顺序
  })

  const roomAmounts = sortedDates.map(date => dateMap.get(date).roomAmount)
  const snackAmounts = sortedDates.map(date => dateMap.get(date).snackAmount)
  const adjustAmounts = sortedDates.map(date => dateMap.get(date).adjustAmount)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const date = params[0].name
        const roomAmount = params[0].value
        const snackAmount = params[1].value
        const adjustAmount = params[2].value
        const total = roomAmount + snackAmount + adjustAmount
        return `${date}<br/>
           房间费: ¥${formatNumber(roomAmount)}<br/>
           商品费: ¥${formatNumber(snackAmount)}<br/>
           调整费: ¥${formatNumber(adjustAmount)}<br/>
           总计: ¥${formatNumber(total)}`
      }
    },
    legend: {
      data: ['房间费', '商品费', '调整费'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '48px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: sortedDates,
      axisLabel: {
        interval: 0,
        rotate: statsPeriod.value === 'day' ? 45 : 0,
        textStyle: {
          fontSize: 12
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => {
          return `¥${formatNumber(value)}`
        }
      }
    },
    series: [
      {
        name: '房间费',
        type: 'bar',
        data: roomAmounts,
        stack: 'total',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#67C23A' },
              { offset: 1, color: '#95D475' }
            ]
          }
        },
        emphasis: {
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: '#85CE61' },
                { offset: 1, color: '#67C23A' }
              ]
            }
          }
        }
      },
      {
        name: '商品费',
        type: 'bar',
        data: snackAmounts,
        stack: 'total',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#E6A23C' },
              { offset: 1, color: '#F3D19E' }
            ]
          }
        },
        emphasis: {
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: '#EEB639' },
                { offset: 1, color: '#E6A23C' }
              ]
            }
          }
        }
      },
      {
        name: '调整费',
        type: 'bar',
        data: adjustAmounts,
        stack: 'total',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#F56C6C' },
              { offset: 1, color: '#FDB9B9' }
            ]
          }
        },
        emphasis: {
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: '#F56C6C' },
                { offset: 1, color: '#F78989' }
              ]
            }
          }
        }
      }
    ]
  }

  chart.setOption(option)
}

// 初始化图表
const initChart = () => {
  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value)
}

// 修改 handleDateChange 函数，添加默认值处理
const handleDateChange = async (val) => {
  try {
    loading.value = true
    // 如果没有选择日期，使用默认范围
    const [start, end] = val || defaultDateRange.value
    const response = await reportAPI.getReportByDateRange(
      start.toISOString().split('T')[0],
      end.toISOString().split('T')[0]
    )
    reportData.value = response
    updateChart()
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}

// 处理周期切换
const handlePeriodChange = () => {
  updateChart()
}

// 监听窗口大小变化
window.addEventListener('resize', () => {
  chart?.resize()
})

onMounted(() => {
  initChart()
  // 设置默认日期范围
  dateRange.value = defaultDateRange.value
  fetchReportData()
})
</script>

<style scoped>
.report-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.report-card {
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-cards {
  margin: 20px 0;
}

.summary-card {
  text-align: center;
  transition: all 0.3s ease;
}

.summary-card:hover {
  transform: translateY(-5px);
}

.summary-card :deep(.el-card__header) {
  padding: 10px;
  font-size: 16px;
  font-weight: bold;
}

.amount {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.total .amount {
  color: #409EFF;
}

.room .amount {
  color: #67C23A;
}

.snack .amount {
  color: #E6A23C;
}

.adjustment .amount {
  color: #F56C6C;
}

.chart-container {
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.chart {
  height: 500px;
  width: 100%;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .summary-cards :deep(.el-col) {
    margin-bottom: 10px;
  }
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.el-radio-group {
  margin-right: 16px;
}

:deep(.el-date-editor) {
  width: 320px;
}
</style> 